<template>
  <div ref="chartContainer" style="width: 100%; height: 330px"></div>
</template>

<script>
import { ref, watch, onMounted } from 'vue'
import * as echarts from 'echarts'

export default {
  name: 'LineChart',
  props: {
    seriesData: {
      type: Array,
      required: true
    },
    categoryData: {
      type: Array,
      required: true
    },
    name: {
      type: String
    }
  },
  setup(props) {
    const chartContainer = ref(null)
    let chartInstance = null

    const initChart = () => {
      if (chartContainer.value) {
        if (!chartInstance) {
          chartInstance = echarts.init(chartContainer.value)
        }

        const options = {
          title: {
            text: props.name
          },
          tooltip: {
            trigger: 'axis'
          },
          xAxis: {
            type: 'category',
            data: props.categoryData
          },
          yAxis: {
            type: 'value'
          },
          series: props.seriesData
        }

        chartInstance.setOption(options)
      }
    }

    onMounted(() => {
      initChart()
    })

    watch(
      () => [props.seriesData, props.categoryData],
      () => {
        initChart()
      },
      { deep: true }
    )

    return {
      chartContainer
    }
  }
}
</script>

<style scoped>
/* 如果需要，添加样式 */
</style>
